package com.flying.acls.adapter.spring;

import com.flying.acls.model.ExprType;
import com.flying.acls.model.PermsType;
import com.flying.acls.model.QAclEntry;
import com.flying.acls.model.ResType;
import com.flying.acls.model.jdbc.AclEntryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;

public class AclEntryFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private AclEntryRepository aclEntryRepository;

    private Collection<AclEntryConfigAttribute> acas = new ArrayList<>();

    @PostConstruct
    private void loadResExprDefinitions() {
        QAclEntry qAclEntry = QAclEntry.aclEntry;
        aclEntryRepository.findAll(qAclEntry.resExpr.type.eq(ResType.URL)
                .and(qAclEntry.permsExpr.type.eq(PermsType.HTTP))).forEach(aclEntry -> {
            acas.add(new AclEntryConfigAttribute(aclEntry));
        });
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        return acas.stream().filter(aclEntryConfigAttribute -> {
            if (aclEntryConfigAttribute.getAclEntry().getResExpr().getExprType() == ExprType.DIRECT) {
                RequestMatcher matcher = new AntPathRequestMatcher(aclEntryConfigAttribute.getAclEntry().getResExpr().getExpression());
                return matcher.matches(fi.getHttpRequest());
            }
            return true;
        }).collect(Collectors.toList());
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return acas.stream().map(aclEntryConfigAttribute -> (ConfigAttribute) aclEntryConfigAttribute).collect(Collectors.toList());
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(FilterInvocation.class);
    }
}
